package com.bawei.module_goods.ui

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_goods.R
import com.bawei.module_goods.entity.DetailEntity
import com.bawei.module_goods.network.GoodsApi
import com.bawei.lib_net.RetrofitFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FootPrintActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_foot_print)
        val recyclerView = findViewById<RecyclerView>(R.id.rv_foot_print)
        recyclerView.layoutManager = LinearLayoutManager(this)

        // 返回按钮点击关闭页面
        findViewById<android.widget.ImageView>(R.id.ivBack)?.setOnClickListener { finish() }

        lifecycleScope.launch {
            val detailList = fetchFootPrintDetailList()
            if (detailList.isNotEmpty()) {
                recyclerView.adapter = FootPrintAdapter(detailList)
            } else {
                Toast.makeText(this@FootPrintActivity, "暂无可展示的足迹", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 返回List<Pair<DetailEntity, viewCount>>
    private suspend fun fetchFootPrintDetailList(): List<Pair<DetailEntity, Int?>> {
        return withContext(Dispatchers.IO) {
            val api = RetrofitFactory.getRetrofitFactory().create(GoodsApi::class.java)
            val response = api.getFootPrint()
            if (response.code == 200) {
                val records = response.data?.records ?: emptyList()
                // 并发查详情，保留viewCount
                val deferredList = records.mapNotNull { record ->
                    val goodsId = record.goodsId
                    if (goodsId != null) {
                        async {
                            try {
                                val detailResp = api.getGoodsDetail(goodsId)
                                if (detailResp.code == 200 && detailResp.data != null) {
                                    Pair(detailResp.data, record.viewCount)
                                } else null
                            } catch (e: Exception) {
                                null
                            }
                        }
                    } else null
                }
                deferredList.mapNotNull { it.await() }
            } else {
                emptyList()
            }
        }
    }
} 